<?php
// +----------------------------------------------------------------------
// | Quotes [ 只为给用户更好的体验]**[我知道发出来有人会盗用,但请您留版权]
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 零度  <2109877665@qq.com>          盗用不留版权,你就不配拿去!
// +----------------------------------------------------------------------
// | Date: 2019年08月20日
// +----------------------------------------------------------------------

/**
     * 判断最近的API服务器接口/获取连接耗时
     *
     * @param array/string $data_URl    如果是域名组数，那么就会自动过滤组数中异常的服务器并选择从本站连接最快的地址,如果是单个域名,那么返回连接耗时
     * @return string
	 *
	 *
	 *组数例如（返回：从本站连接最快地址【http://dns.99ypay.cn/】）:	
	 *		$Instant_url_list = array(
	 *			'http://ds.99ypay.cn/',
	 *			'http://dns.99ypay.cn/',
	 *			'http://qinjireno.gz01.bdysite.com/',
	 *			'http://www.qq1111mzz.cn/'
	 *		);
	 *单个域名输入(返回:连接耗时【152.345】)
	 *		 	http_runtime('http://dns.99ypay.cn/');
     */
function http_runtime($data_URl)//@data_URl
{
	for($i=0; $i<3; $i++)
	{
		list($usec, $sec) = explode(' ', microtime());  
        $t1 = ((float)$usec + (float)$sec); 
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $data_URl);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		$httpheader[] = "Accept:*/*";
		$httpheader[] = "Accept-Encoding:gzip,deflate,sdch";
		$httpheader[] = "Accept-Language:zh-CN,zh;q=0.8";
		$httpheader[] = "Connection:close";
		curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
		curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Linux; U; Android 4.0.4; es-mx; HTC_One_X Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0");
		curl_setopt($ch, CURLOPT_ENCODING, "gzip");
		curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HEADER, 1);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
		$ret = curl_exec($ch);
		$httpcode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
		curl_close($ch);
		list($usec, $sec) = explode(' ', microtime());  
        $t2 = ((float)$usec + (float)$sec); 
		$num= $t2-$t1;
		$mis+=$num;
	}
		if(is_array($data_URl))
		{
			$Apis_ms = 999;
			foreach ($data_URl as $key => $val) {
			$ms_ = http_runtime($data_URl[$key]);
			preg_match('#<font color=red>(.*?)</font>#',$ms_,$z_t);
			preg_match('#<font color=green>(.*?)</font>#',$ms_,$m_s);
			$ms = $m_s[1];
				if($Apis_ms>$ms and $z_t[1]!='异常'){//将第一个默认为最小的值和数组中的所有值比较，如果默认的最小值比其他的值大，那叫交换，最终遍历完后，$min中存储的就是数组中的最小的值
					$Apis_ms = $ms;
					$Apis_url = $data_URl[$key];
				}
			}
			return $Apis_url.$Apis_ms; //得到连接耗时
		}else{
			if($httpcode==200)
				if(round(($mis * 1000)/3,3)<800)//如果大于800则可能影响速度,所以颜色需要改变
					return '<font color=green>'.round(($mis * 1000)/3,3).'</font>'; //得到连接耗时
				else
					return '<font color=red>'.round(($mis * 1000)/3,3).'</font>'; //得到连接耗时
			else
				return '<font color=red>异常</font>'; //得到连接耗时
		}
}
function Get_Notify($row){
	global $Instant_Api,$DB,$conf,$date;
	$crontime=time()+10;//当前时间戳 下次执行时间)
	//开始回调金额
		$DB->exec("update `pay_notify` set `crontime`='{$crontime}' WHERE `id`='{$row['id']}'");//更新数据
		if($row['nums']==1){
			$DB->exec("update `pay_notify` set `status`='2',`pay_msg`='订单不存在或支付金额不正确' WHERE `id`='{$row['id']}'");//更新数据
		}elseif($row['status']==0){
			$count=$DB->query("SELECT count(*) from `pay_notify` where `status`='0' and `money`='{$row['money']}'")->fetchColumn();
			if($count>1){
				$DB->exec("DELETE FROM `pay_notify` WHERE `status`='0' and `money`='{$row['money']}' limit 1");//删除重复的回调金额数据
			}
			if($row['money']>=0.01){//判断是否是收入金额
				$data = $Instant_Api->Submit_submit($row['api_type'],$row['money']);
				//if($data['code']==-1)$data = $Instant_Api->Submit_submit(urlencode($row['api_type']),$row['money']);
				$json = json_decode($data,true);
			}
			if($json['code']==-1 && $row['status']==0){
				$DB->exec("update `pay_notify` set `nums`=`nums`+'1',`pay_msg`='{$json['msg']}' WHERE `id`='{$row['id']}'");//更新数据
			}else{
				$DB->exec("update `pay_notify` set `status`='1',`pay_msg`='回调成功：{$data}' WHERE `id`='{$row['id']}'");//更新数据
			}
		}
	$data = 'Notify-Ok_'.date("H:i:s");
	return $data;
}
function do_notify($url){
	$ch=curl_init($url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Linux; U; Android 4.4.1; zh-cn; R815T Build/JOP40D) AppleWebKit/533.1 (KHTML, like Gecko)Version/4.0 MQQBrowser/4.5 Mobile Safari/533.1');
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
	$return=curl_exec($ch);
	curl_close($ch);
	if(strpos($return,'success')!==false){
		return true;
	}else{
		return false;
	}
}
function get_curl($url,$post=0,$referer=0,$cookie=0,$header=0,$ua=0,$nobaody=0){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	$httpheader[] = "Accept:*/*";
	$httpheader[] = "Accept-Encoding:gzip,deflate,sdch";
	$httpheader[] = "Accept-Language:zh-CN,zh;q=0.8";
	$httpheader[] = "Connection:close";
	curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
	if($post){
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
	}
	if($header){
		curl_setopt($ch, CURLOPT_HEADER, TRUE);
	}
	if($cookie){
		curl_setopt($ch, CURLOPT_COOKIE, $cookie);
	}
	if($referer){
		if($referer==1){
			curl_setopt($ch, CURLOPT_REFERER, 'http://m.qzone.com/infocenter?g_f=');
		}else{
			curl_setopt($ch, CURLOPT_REFERER, $referer);
		}
	}
	if($ua){
		curl_setopt($ch, CURLOPT_USERAGENT,$ua);
	}else{
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Linux; U; Android 4.4.1; zh-cn; R815T Build/JOP40D) AppleWebKit/533.1 (KHTML, like Gecko)Version/4.0 MQQBrowser/4.5 Mobile Safari/533.1');
	}
	if($nobaody){
		curl_setopt($ch, CURLOPT_NOBODY,1);
	}
	curl_setopt($ch, CURLOPT_ENCODING, "gzip");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	$ret = curl_exec($ch);
	curl_close($ch);
	return $ret;
}
function real_ip(){
$ip = $_SERVER['REMOTE_ADDR'];
if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
	foreach ($matches[0] AS $xip) {
		if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
			$ip = $xip;
			break;
		}
	}
} elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
	$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['HTTP_CF_CONNECTING_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CF_CONNECTING_IP'])) {
	$ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
} elseif (isset($_SERVER['HTTP_X_REAL_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_REAL_IP'])) {
	$ip = $_SERVER['HTTP_X_REAL_IP'];
}
return $ip;
}

function DeleteHtml($str) 
{ 
    $str = trim($str); //清除字符串两边的空格
    $str = preg_replace("/\t/","",$str); //使用正则表达式替换内容，如：空格，换行，并将替换为空。
    $str = preg_replace("/\r\n/","",$str); 
    $str = preg_replace("/\r/","",$str); 
    $str = preg_replace("/\n/","",$str); 
    $str = preg_replace("/ /","",$str);
    $str = preg_replace("/  /","",$str);  //匹配html中的空格
    return trim($str); //返回字符串
}

function checkServerSatatus($ip) {
	$str = null;
	$ip = str_replace("http://","",$ip);
	$ip = str_replace("/","",$ip);
	list($usec, $sec) = explode(' ', microtime());  
    $t1 = ((float)$usec + (float)$sec); 
	$fp = @fsockopen($ip,80,$errno,$errstr,10);
	if (!$fp) {
		return array('code'=>0,'msg'=>'不在线[异常]');
	} else {
		fclose($fp);
		list($usec, $sec) = explode(' ', microtime());  
        $t2 = ((float)$usec + (float)$sec); 
		$num= $t2-$t1;
		$mis+=$num;
		$mis = round((round(($mis * 1000)/4,3) * 10)/2,3);
		$get_ip_city = get_ip_city($ip)['Result'];
			if($mis<100)//如果大于800则可能影响速度,所以颜色需要改变
				$Ping = '<font color=green>'.$mis.'</font>'; //得到连接耗时
			elseif($mis<150)//如果大于800则可能影响速度,所以颜色需要改变
				$Ping = '<font color=#ff3399>'.$mis.'</font>'; //得到连接耗时
			else
				$Ping = '<font color=red>'.$mis.'</font>'; //得到连接耗时
		return array('code'=>1,'msg'=>'在线[正常]','IP'=>$get_ip_city['IP'],'Country'=>$get_ip_city['Country'],'Ping'=>$Ping);
	}
}
function get_ip_city($ip = ''){
    if($ip == ''){
        $ip = real_ip();
    }
    $ip = str_replace("/","",$ip); 
    $ip = str_replace("https:","",$ip); 
    $ip = str_replace("http:","",$ip);
	$url = "http://www.882667.com/ip_{$ip}.html";
    $data = DeleteHtml(get_curl($url));
	$IP_IP = getSubstr($data, '><spanclass="shenlansezidazi">', "</span></a>");
	$Country = getSubstr($data, '地区：<spanclass="shenlansezi">', "</span><p>");
	$Result=array('IP'=>explode('><spanclass="shenlansezidazi">',$IP_IP)[1],'Country'=>$Country);
	if(!$IP_IP or !$Country){
		$url = "https://ipchaxun.com/{$ip}";
		$data = DeleteHtml(get_curl($url));
		$explode = explode('</span><spanclass="value">',$data);
		$Result=array('IP'=>explode('</span></label><label>',$explode[1])[0],'Country'=>explode('</span></label><label>',$explode[2])[0]);
	}
	/*
	
	$url = "http://ip.webmasterhome.cn/";
	$post = "ip=".$ip;
    $data = get_curl($url?$post,$post);
	$json = json_decode($data, true);
	$Result=array('IP'=>$json['text']['ip'],'Country'=>$json['text']['ip2region']);
	*/
	if(!$Result['IP'] or !$Result['IP']){
		$Result=array('IP'=>'无法读取','Country'=>'无法读取');
	}
	$return=array('code'=>1,'msg'=>'成功','Result'=>$Result);
	return $return;
}
		
function send_mail($to, $sub, $msg) {
	global $conf;
		if($conf['mail_type']=='接口发件'){
			$mail_api = 'http://1.mail.qqzzz.net/';
		}
	if($mail_api) {
		$post[sendto]=$to;
		$post[title]=$sub;
		$post[content]=$msg;
		$post[user]=$conf['mail_name'];
		$post[pwd]=$conf['mail_pwd'];
		$post[nick]=$conf['sitename'];
		$post[host]=$conf['mail_smtp'];
		$post[port]=$conf['mail_port'];
		$post[ssl]=$conf['mail_port']==465?1:0;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$mail_api);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($post));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		$ret = curl_exec($ch);
		curl_close($ch);
		if($ret=='1')return true;
		else return $ret;
	} elseif($conf['mail_type']=='本地发件一') {
		include_once ROOT.'Core/Core_Class/Smtp.Class.1.php';
		$From = $conf['mail_name'];
		$Host = $conf['mail_smtp'];
		$Port = $conf['mail_port'];
		$SMTPAuth = 1;
		$Username = $conf['mail_name'];
		$Password = $conf['mail_pwd'];
		$Nickname = $conf['sitename'];
		$SSL = $conf['mail_port']==465?1:0;
		$mail = new SMTP($Host , $Port , $SMTPAuth , $Username , $Password , $SSL);
		$mail->att = array();
		if($mail->send($to , $From , $sub , $msg, $Nickname)) {
			return true;
		} else {
			return $mail->log;
		}
	} elseif($conf['mail_type']=='本地发件二') {
		include_once ROOT.'Core/Core_Class/Smtp.Class.2.php';
		$From = $conf['mail_name'];
		$Host = $conf['mail_smtp'];
		$Port = $conf['mail_port'];
		$SMTPAuth = 1;
		$Username = $conf['mail_name'];
		$Password = $conf['mail_pwd'];
		$Nickname = $conf['sitename'];
		$SSL = $conf['mail_port']==465?1:0;
		$smtp = new Smtp($Host , $Port , $SMTPAuth , $Username , $Password);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
		$smtp->debug = false;//是否显示发送的调试信息
		$state = $smtp->sendmail($to , $From , $sub, $msg , "HTML");
		if($state) {
			return true;
		} else {
			return $mail->log;
		}
	}
}
function daddslashes($string, $force = 0, $strip = FALSE) {
	!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
	if(!MAGIC_QUOTES_GPC || $force) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = daddslashes($val, $force, $strip);
			}
		} else {
			$string = addslashes($strip ? stripslashes($string) : $string);
		}
	}
	return $string;
}

function checkIfActive($string) {
	$array=explode(',',$string);
	$php_self=substr($_SERVER['REQUEST_URI'],strrpos($_SERVER['REQUEST_URI'],'/')+1,strrpos($_SERVER['REQUEST_URI'],'.')-strrpos($_SERVER['REQUEST_URI'],'/')-1);
	if (in_array($php_self,$array)){
		return 'active';
	}else
		return null;
}
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	$ckey_length = 4;
	$key = md5($key ? $key : ENCRYPT_KEY);
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);
	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);
	$result = '';
	$box = range(0, 255);
	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}
	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}
	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}
	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}
}

function random($length, $numeric = 0) {
	$seed = base_convert(md5(microtime().$_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
	$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
	$hash = '';
	$max = strlen($seed) - 1;
	for($i = 0; $i < $length; $i++) {
		$hash .= $seed{mt_rand(0, $max)};
	}
	return $hash;
}
function showmsg($content = '未知的异常',$type = 4,$back = false)
{
switch($type)
{
case 1:
	$panel="success";
break;
case 2:
	$panel="info";
break;
case 3:
	$panel="warning";
break;
case 4:
	$panel="danger";
break;
}

echo '<div class="panel panel-'.$panel.'">
      <div class="panel-heading">
        <h3 class="panel-title">提示信息</h3>
        </div>
        <div class="panel-body">';
echo $content;

if ($back) {
	echo '<hr/><a href="'.$back.'"><< 返回上一页</a>';
}
else
    echo '<hr/><a href="javascript:history.back(-1)"><< 返回上一页</a>';

echo '</div>
    </div>';
}
function sysmsg($msg = '未知的异常',$die = true) {
    ?>  
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>站点提示信息</title>
        <style type="text/css">
html{background:#eee}body{background:#fff;color:#333;font-family:"微软雅黑","Microsoft YaHei",sans-serif;margin:2em auto;padding:1em 2em;max-width:700px;-webkit-box-shadow:10px 10px 10px rgba(0,0,0,.13);box-shadow:10px 10px 10px rgba(0,0,0,.13);opacity:.8}h1{border-bottom:1px solid #dadada;clear:both;color:#666;font:24px "微软雅黑","Microsoft YaHei",,sans-serif;margin:30px 0 0 0;padding:0;padding-bottom:7px}#error-page{margin-top:50px}h3{text-align:center}#error-page p{font-size:9px;line-height:1.5;margin:25px 0 20px}#error-page code{font-family:Consolas,Monaco,monospace}ul li{margin-bottom:10px;font-size:9px}a{color:#21759B;text-decoration:none;margin-top:-10px}a:hover{color:#D54E21}.button{background:#f7f7f7;border:1px solid #ccc;color:#555;display:inline-block;text-decoration:none;font-size:9px;line-height:26px;height:28px;margin:0;padding:0 10px 1px;cursor:pointer;-webkit-border-radius:3px;-webkit-appearance:none;border-radius:3px;white-space:nowrap;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-webkit-box-shadow:inset 0 1px 0 #fff,0 1px 0 rgba(0,0,0,.08);box-shadow:inset 0 1px 0 #fff,0 1px 0 rgba(0,0,0,.08);vertical-align:top}.button.button-large{height:29px;line-height:28px;padding:0 12px}.button:focus,.button:hover{background:#fafafa;border-color:#999;color:#222}.button:focus{-webkit-box-shadow:1px 1px 1px rgba(0,0,0,.2);box-shadow:1px 1px 1px rgba(0,0,0,.2)}.button:active{background:#eee;border-color:#999;color:#333;-webkit-box-shadow:inset 0 2px 5px -3px rgba(0,0,0,.5);box-shadow:inset 0 2px 5px -3px rgba(0,0,0,.5)}table{table-layout:auto;border:1px solid #333;empty-cells:show;border-collapse:collapse}th{padding:4px;border:1px solid #333;overflow:hidden;color:#333;background:#eee}td{padding:4px;border:1px solid #333;overflow:hidden;color:#333}
        </style>
    </head>
    <body id="error-page">
        <?php echo '<h3>站点提示信息</h3>';
        echo $msg; ?>
    </body>
    </html>
    <?php
    if ($die == true) {
        exit;
    }
}
function getdomain($url){//获取域名
	$arr=parse_url($url);
	return $arr['host'];
}

function getQQNick($qq){//获取QQ网名
   $get_info = file_get_contents('http://r.qzone.qq.com/fcg-bin/cgi_get_portrait.fcg?get_nick=1&uins='.$qq);
    //转换编码
    $get_info = mb_convert_encoding($get_info, "UTF-8", "GBK");
    //对获取的json数据进行截取并解析成数组
    $name = json_decode(substr($get_info,17,-1),true);
 return $name[$qq][6];
}

//https://www.jisuapi.com/my/api?totalnum=2&authnum=1 急速数据接口  9元1W次
function qrcode($qrcode = 'https://ww1.sinaimg.cn/large/005BYqpggy1fxjot06nomj309l09cwez.jpg')//二维码解码
{
	global $conf;
	$post['data'] = $qrcode;
	$result=get_curl('https://cli.im/Api/Browser/deqr',$post);//免费解码,不可用时调用付费
	$json = json_decode($result, true);
	if($json['status']!=1){//https://api.jisuapi.com/qrcode/read?qrcode=http://api.jisuapi.c&appkey=b4134d78d665ad1c
		$result=get_curl('https://api.jisuapi.com/qrcode/read?appkey=b4134d78d665ad1c&qrcode='.$post['data']);//付费解码(99.99%能解)
		$json = json_decode($result, true);
		if($json['status']==0 and $json['result']!=false)
			return $json['result'];
		else
			return false;
	}else{
		return $json['data']['RawData'];
	}
}
/*以下是取中间文本的函数 
  getSubstr=调用名称
  $str=预取全文本 
  $leftStr=左边文本
  $rightStr=右边文本
*/
function getSubstr($str, $leftStr, $rightStr)
{
    $left = strpos($str, $leftStr);
    //echo '左边:'.$left;
    $right = strpos($str, $rightStr,$left);
    //echo '<br>右边:'.$right;
    if($left < 0 or $right < $left) return '';
    return substr($str, $left + strlen($leftStr), $right-$left-strlen($leftStr));
}
//只取字母、数字、汉子
function match_chinese($chars,$encoding='utf8')
{
$pattern =($encoding=='utf8')?'/[\x{4e00}-\x{9fa5}a-zA-Z0-9]/u':'/[\x80-\xFF]/';
preg_match_all($pattern,$chars,$result);
$temp =join('',$result[0]);
return $temp;
}
function status_zt($zt)//cookie检测
{
	if($zt!=1)
		return '<font color=red>禁封</font>';
	else
		return '<font color=green>正常</font>';
}
function checkauth($url,$authcode) {
	global $DB, $ip;
	$row=$DB->query("SELECT * FROM `pay_check` WHERE `url`='{$url}' and `authcode`='{$authcode}' limit 1")->fetch();
	if ($row) {
		pay_cron_url($url,$authcode);//写入记录
		return true;
	} else {
		return false;
	}
}
function checkauth_pid_key($url,$authcode,$Instant_pid,$Instant_key) {
	global $DB;
	$Coheck_row=$DB->query("SELECT * FROM pay_check WHERE url='{$url}' limit 1")->fetch();
	$Cloud_row=$DB->query("SELECT * FROM pay_cloud WHERE qq='{$Coheck_row['qq']}' limit 1")->fetch();
	if ($Coheck_row) {
		if($Coheck_row['status']==0 or $authcode!=$Coheck_row['authcode'] or $Instant_pid!=$Cloud_row['pid'] or $Instant_key!=$Cloud_row['key']){
			return false;
		}else{
			pay_cron_url($url,$authcode);
			return true;
		}
	} else {
		return false;
	}
}
//源码泄露  授权码私自更改  云端泄露检测写入
function pay_cron_url($url,$authcode) {
	global $DB, $date, $ip;
	//开始判断授权码
	$row_url=$DB->query("SELECT * FROM `pay_cron_url` WHERE `url`='{$url}' limit 1")->fetch();
	$row_authcode=$DB->query("SELECT * FROM `pay_cron_url` WHERE `authcode`='{$authcode}' limit 1")->fetch();
	$row_ip=$DB->query("SELECT * FROM `pay_cron_url` WHERE `ip`='{$ip}' limit 1")->fetch();
	//当前数据库不存在此IP则记录
	if(!$row_ip or !$row_url){
		$DB->exec("INSERT INTO `pay_cron_url` (`url`,`authcode`, `ip`, `nums`,`crontime`) VALUES ('{$url}','{$authcode}','{$ip}','1','0')");
	}else{
		$DB->exec("update `pay_cron_url` set `nums` =`nums`+'1' where `ip`='{$ip}'");
	}
	//检测同一个授权码是否搭建两个系统以上
	$ip_nums=$DB->query("SELECT count(*) from `pay_cron_url` WHERE `url`='{$url}'")->fetchColumn();
	if($ip_nums>2){
		//取一个真正正版的(访问最多)
		$y_nums = $DB->query("SELECT * FROM `pay_cron_url`  where `authcode`='{$authcode}' order by nums desc limit 1")->fetch();
			
		//取一个盗版的(访问最少)
		$n_nums = $DB->query("SELECT * FROM `pay_cron_url`  where `authcode`='{$authcode}' order by nums asc limit 1")->fetch();
		
		//判断是否记录到泄露源码的嫌疑
		if($y_nums['nums']>30 and $n_nums['nums']<10 and $y_nums['ip']!=$n_nums['ip']){
			//加入到泄露源码嫌疑
			$DB->query("update `pay_check` set `beizhu` ='存在泄露源码嫌疑' where `url`='{$url}'");
		}
		//开始对比，是否是更换服务器,非更换服务器则禁封
		if($y_nums['nums']>50 and $n_nums['nums']>20 and $y_nums['ip']!=$n_nums['ip']){
			//第二站点未关闭,认定为泄露源码
			$DB->query("update `pay_check` set `status` ='0', `beizhu` ='禁封原因:可能存在泄露源码嫌疑' where `url`='{$url}'");//禁封
		}
	}
}
//取支付宝 QQ财付通二维码验证正版函数
function pay_check_ip() {
	global $DB, $date, $ip;
	$rs=$DB->query("SELECT * FROM pay_cron_url WHERE `ip`='{$ip}' order by nums desc limit 99999");
	while($res = $rs->fetch())
	{
		$row=$DB->query("SELECT * FROM `pay_check` WHERE `url`='{$res['url']}' order by addtime desc limit 1")->fetch();
		if($row['status']==1)
		{
			return $row;
		}
	}
}

?>